import json

from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from meiduo_project import settings


class QQLoginURLView(View):

    def get(self, request):
        # 使用QQloginTool生成跳转链接
        # 导入
        from QQLoginTool.QQtool import OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="xxx")
        # 获取扫码页面
        login_url = oauth.get_qq_url()
        # 返回响应
        return JsonResponse({"code": 0, "login_url": login_url})


class OauthView(View):
    def get(self, request):
        # 1获取code
        code = request.GET.get("code")

        # 2根据code获取token
        # 导入
        from QQLoginTool.QQtool import OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='xxx')
        # 获取token
        access_token = oauth.get_access_token(code)

        # 3根据token获取openid
        openid = oauth.get_open_id(access_token)
        # 根据openid去数据库查询OAuthQQUser账号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print(e)
            openid = generate_access_token(openid)
            return JsonResponse({"code": 400, "access_token": openid})
        else:
            login(request, qquser.user)
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("username", qquser.user.username)

        return response

    def post(self, request):

        body = request.body
        data_dict = json.loads(body)
        # 获取请求参数手机号密码短信验证码openid
        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")
        openid = check_access_token(openid)

        # 根据手机号 查询是否已经注册
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            print(e)
            # 没有注册
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 已经注册了
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "账号或密码错误"})

        # 已经注册密码验证密码正确直接绑定用户和openid
        # 绑定user和openid
        try:
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "该账号已经绑定了"})

        # 状态保持
        login(request, user)
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.set_cookie("username", user.username)
        # 返回响应
        return response
